#version 430

in vec3 VertPos;
in vec3 N;
in vec2 TexCoords;

uniform vec3 viewPos;

// Light information
uniform vec3 LightPosition;				// Light position in eye view
uniform vec3 Ia;						// Ambient intensity
uniform vec3 Id;						// Diffuse and specular light intensity
uniform float MinAttenuation;			// Minimum attenuation for the light (really intense light like sun, moon, etc)
// Object material
uniform vec3 Kd;						// Diffuse reflection coefficient (0 - 1)
uniform vec3 Ka;						// Ambient Reflection Coefficient
uniform vec3 Ks;						// Specular Reflection Coefficient
////////////////

uniform bool UseNormalTexture;
uniform sampler2D NormalTexture;

uniform bool UseDepthTexture;
uniform sampler2D DepthTexture;

uniform bool UseSpecularTexture;
uniform sampler2D SpecularTexture;

uniform bool UseDiffuseTexture;
uniform sampler2D DiffuseTexture;


float dotRV;

layout( location = 0 ) out vec4 FragColour;


in vec4 ViewSpaceVertPos;

uniform vec3 fogColour;
uniform float fogDensity;

vec3 calcFog(vec3 colour) {
	float fogCoord = abs(ViewSpaceVertPos.z / ViewSpaceVertPos.w);
	float factor = exp(-pow(fogDensity*fogCoord, 2.0)); // e^(-[(fd*fc)^2]); 1/(e^[(fd*fc)^2])
	factor = clamp(factor, 0.0, 1.0);
	return mix(fogColour, colour, factor);
}

vec3 RGBToNormal(vec3 rgb) { return 2.0 * rgb - 1.0; }

vec3 ads()
{
	vec3 LightVector = LightPosition - VertPos;

	vec3 L = normalize(LightVector);      
	vec3 V = -normalize(viewPos - VertPos);

	vec3 dfuse = vec3(1.f);	
	if (UseDiffuseTexture)
		dfuse = texture(DiffuseTexture, TexCoords).rgb;
	
	vec3 specl = dfuse;
	if (UseSpecularTexture)
		specl = texture(SpecularTexture, TexCoords).rgb;

	vec3 Norm = N;
	if (UseNormalTexture)
		Norm = RGBToNormal(texture(NormalTexture, TexCoords).rgb);


	vec3 AmbientTerm = (Ia * Ka * dfuse);									//Ambient
	float A = 1.0f - pow(length(LightVector) / 100.f, 2);
	float Attenuation = max(A, MinAttenuation);
	vec3 DiffuseTerm = Attenuation * dfuse * Kd * max(dot(Norm,L), 0.0);	//Diffuse
	vec3 R = -reflect(L, Norm);
	vec3 SpecularTerm = Attenuation * Id * specl * Ks * pow(max(dot(R, V), 0.0), 2);
	SpecularTerm = clamp(SpecularTerm, 0.0, 1.0);							//Specular

	
	vec3 I = AmbientTerm + DiffuseTerm + SpecularTerm;
	I = clamp(I, 0.0, 1.0);

	return I;
	/*
	vec3 n = normalize(Norm);
		
	vec3 l = normalize( vec3(LightPosition) - VertPos);

	float df = max( dot(l,n), 0.0);
	float sf = 0.0f;

	if (df > 0.0f) 
	{
		vec3 v = normalize(vec3(VertPos));
		vec3 r = reflect(l, n);
		sf = max(dot(r,v), 0.0f);
	}
	
	return dfuse;
	*/
}

//Only use diffuse for testing (TO BE REMOVED)
vec3 diffuse()
{
	return texture(DiffuseTexture, TexCoords).rgb;
}

void main() {

   FragColour = vec4(calcFog(ads()),1.0);
   //FragColour = vec4(diffuse(),1.0);
}